import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getLoginUser, listUserByPage } from '@/api/user'

export const useUserStore = defineStore('user', () => {
    const userInfo = ref({
        id: '',
        userAccount: '',
        userName: '',
        userAvatar: '',
        userProfile: '',
        userRole: '',
        balance: 0
    })
    const token = ref('')
    const isAdmin = ref(false)

    // 获取用户信息
    const fetchUserInfo = async () => {
        try {
            const res = await getLoginUser()
            const userRes = await listUserByPage({
                current: 1,
                pageSize: 1,
                id: res.data.id
            })
            if (userRes.code === 0 && userRes.data.records && userRes.data.records.length > 0) {
                const userData = userRes.data.records[0]
                userInfo.value = {
                    id: userData.id || '',
                    userAccount: userData.userAccount || '',
                    userName: userData.userName || '',
                    userAvatar: userData.userAvatar || '',
                    userProfile: userData.userProfile || '',
                    userRole: userData.userRole || '',
                    balance: userData.balance ?? 0
                }
                isAdmin.value = res.data.userRole === 'admin'
                return true
            }
            return false
        } catch (error) {
            console.error('获取用户信息失败:', error)
            return false
        }
    }

    // 设置用户信息
    const setUserInfo = info => {
        userInfo.value = info
        isAdmin.value = info?.userRole === 'admin'
    }

    // 清除用户信息
    const clearUserInfo = () => {
        userInfo.value = null
        isAdmin.value = false
        token.value = ''
    }

    // 检查是否已登录
    const isLoggedIn = () => {
        return !!userInfo.value
    }

    // 检查是否是管理员
    const checkIsAdmin = () => {
        return isAdmin.value
    }

    return {
        userInfo,
        token,
        isAdmin,
        fetchUserInfo,
        setUserInfo,
        clearUserInfo,
        isLoggedIn,
        checkIsAdmin
    }
})
